package com.b2c.erp.controller.ajax;

import com.alibaba.fastjson.JSON;
import com.b2c.common.utils.DateUtil;
import com.b2c.common.utils.JsonUtil;
import com.b2c.entity.DataRow;
import com.b2c.entity.ErpOrderEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.vo.order.DouYinOrderCountVo;
import com.b2c.entity.enums.EnumUserActionType;
import com.b2c.entity.vo.OrderScanCodeVo;
import com.b2c.interfaces.ExpressCompanyService;
import com.b2c.interfaces.erp.ErpOrderService;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.interfaces.SysThirdSettingService;
import com.b2c.entity.enums.EnumErpOrderSendStatus;
import com.b2c.erp.req.GeneratePickingReq;
import com.b2c.erp.req.GoodsSearchReq;
import com.b2c.erp.req.InvoiceDeleteReq;
import com.b2c.erp.response.ApiResult;
import com.b2c.erp.response.ErpOrderSendShowRes;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 
 */
@RequestMapping(value = "/ajax_order")
@RestController
public class AjaxOrderController {

    @Autowired
    private SysThirdSettingService thirdSettingService;
    @Autowired
    private ErpOrderService orderService;
    @Autowired
    private ExpressCompanyService expressCompanyService;
    @Autowired
    private ErpUserActionLogService logService;



    Logger log = LoggerFactory.getLogger(AjaxOrderController.class);
    /**
     * 获取订单详情
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/get_order_by_num", method = RequestMethod.POST)
    public ApiResult<ErpOrderSendShowRes> getSendGoods(@RequestBody GoodsSearchReq req) {
        if (StringUtils.isEmpty(req.getKey()))
            return new ApiResult<>(400, "参数错误");

//        var invoice = invoiceService.getInvoiceDetail(request.getKey());

        var order = orderService.getOrderEntityByNum(req.getKey());

        if (order == null) return new ApiResult<>(404, "没找到数据");
        var items = orderService.getErpOrderItemsByOrderId(order.getId());
        ErpOrderSendShowRes res = new ErpOrderSendShowRes();
        res.setOrder(order);
        res.setOrderItems(items);

        return new ApiResult<>(0, "SUCCESS", res);
    }

    /**
     * 获取订单（物流单号 或 订单号）
     * @param req
     * @return
     */
    @RequestMapping(value = "/get_order_by_logistics_orderNum", method = RequestMethod.POST)
    public ApiResult<List<OrderScanCodeVo>> getOrderByLogisticsCodeOrorderNum(@RequestBody GoodsSearchReq req) {
        if (StringUtils.isEmpty(req.getKey()))
            return new ApiResult<>(400, "参数错误");

        var orderList = orderService.getOrderAndItemsByLogisticsCodeOrorderNum(req.getKey());

        if (orderList == null) return new ApiResult<>(404, "没找到数据");

        /********组合前台需要的html*******/


        return new ApiResult<>(0, "SUCCESS", orderList);
    }

    @RequestMapping(value = "/get_order_by_orderIdArr", method = RequestMethod.POST)
    public ApiResult<List<OrderScanCodeVo>> getOrderByLogisticsCodeOrorderNum(@RequestBody DataRow req) {

        /********组合前台需要的html*******/
        var result = orderService.getOrderAndItemsByLogisticsCodeOrordeId((ArrayList)req.get("orderIdArr"));

        return new ApiResult<>(0, "SUCCESS",result);
    }

    /***
     * 订单手动选择快递单
     * @return
     */
    @RequestMapping(value = "/order_hand_express", method = RequestMethod.POST)
    public ApiResult<Integer> getOrderSend(@RequestBody DataRow data , HttpServletRequest request) {
        if(StringUtils.isEmpty(data.getString("companyCode")))return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "请选择快递公司");
        if(StringUtils.isEmpty(data.getString("code")))return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "请输入快递单号");

        var ressult = orderService.orderHandExpress(data.getInt("id"),data.getString("company"),data.getString("companyCode"),data.getString("code"));

        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.StockOperation,
                "/ajax_order/order_hand_express","手动选择快递单 ,订单号"+data.getInt("id")+",快递公司 : "+data.getString("company")+" ,快递单号"+data.getString("code")+" 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),ressult.getMsg());

        return new ApiResult<>(ressult.getCode(), ressult.getMsg());

    }

    /***
     * 订单出库（发货）
     * @param req
     * @return
     */
    @RequestMapping(value = "/order_send_confirm", method = RequestMethod.POST)
    public ApiResult<Object> getOrderSend(@RequestBody InvoiceDeleteReq req , HttpServletRequest request) {
        if (req.getId() == null || req.getId().intValue() <= 0) return new ApiResult<>(400, "参数错误");
        var order = orderService.getOrderEntityById(req.getId());
        //订单状态判断
        if (order == null) return new ApiResult<>(401, "订单不存在");
        else if (order.getStatus().intValue() == EnumErpOrderSendStatus.WaitOut.getIndex())
            return new ApiResult<>(402, "订单还没有拣货");
        else if (order.getStatus().intValue() == EnumErpOrderSendStatus.Picking.getIndex())
            return new ApiResult<>(402, "订单正在拣货中，还未完成拣货");
        else if (order.getStatus().intValue() == EnumErpOrderSendStatus.HasSend.getIndex())
            return new ApiResult<>(403, "订单已经发货");
        else if (order.getStatus().intValue() == EnumErpOrderSendStatus.Picked.getIndex()) {
            return new ApiResult<>(402, "订单已拣货未出库");
        }
        //判断订单物流单号信息
        if (StringUtils.isEmpty(order.getLogisticsCode()))
            return new ApiResult<>(405, "订单还没有打印快递单");

        //变更发货状态
        var result = orderService.sendOrder(req.getId());

        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.StockOperation,
                "/ajax_order/order_send_confirm","订单出库（发货） ,订单号"+req.getId()+" , 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),result.getMsg());
//        if(result.getCode()== EnumResultVo.SUCCESS.getIndex()){
//            ygOrderService.updOrderSendStatus(order.getOrder_num(),order.getLogisticsCompany(),order.getLogisticsCompanyCode(),order.getLogisticsCode());
//            return new ApiResult<>(0, "SUCCESS");
//        }else
//            return new ApiResult<>(result.getCode(), result.getMsg());

        return new ApiResult<>(result.getCode(), result.getMsg());
    }


    /**
     * 订单批量确认发货
     * @param request
     * @return
     */
    @RequestMapping(value = "/order_send_confirm_batch", method = RequestMethod.POST)
    public ApiResult<Object> batchOrderSend( HttpServletRequest request,@RequestBody DataRow data ) {
        String orderIds = data.getString("ids");
        if(StringUtils.isEmpty(orderIds)) return new ApiResult<>(401, "参数错误，缺少orderIds");
        //查询订单
        List<ErpOrderEntity> orderList = orderService.getOrderEntityByIds(orderIds);
        if(orderList==null)return new ApiResult<>(401, "参数错误，没有找到订单");


        for (var order:orderList) {

            //订单状态判断
            if (order == null) return new ApiResult<>(401, "订单不存在");
            else if (order.getStatus().intValue() == EnumErpOrderSendStatus.WaitOut.getIndex())
                return new ApiResult<>(402, "订单还没有拣货");
            else if (order.getStatus().intValue() == EnumErpOrderSendStatus.Picking.getIndex())
                return new ApiResult<>(402, "订单正在拣货中，还未完成拣货");
            else if (order.getStatus().intValue() == EnumErpOrderSendStatus.HasSend.getIndex())
                return new ApiResult<>(403, "订单已经发货");
            else if (order.getStatus().intValue() == EnumErpOrderSendStatus.Picked.getIndex()) {
                return new ApiResult<>(402, "订单已拣货未出库");
            }
            //判断订单物流单号信息
            if (StringUtils.isEmpty(order.getLogisticsCode()))
                return new ApiResult<>(405, "订单还没有打印快递单");

            //变更发货状态
            var result = orderService.sendOrder(order.getId());

            //添加系统日志
            logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.StockOperation,
                    "/ajax_order/order_send_confirm", "订单出库（发货） ,订单号" + order.getId() + " , 日期 : " + new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()), result.getMsg());
//        if(result.getCode()== EnumResultVo.SUCCESS.getIndex()){
//            ygOrderService.updOrderSendStatus(order.getOrder_num(),order.getLogisticsCompany(),order.getLogisticsCompanyCode(),order.getLogisticsCode());
//            return new ApiResult<>(0, "SUCCESS");
//        }else
//            return new ApiResult<>(result.getCode(), result.getMsg());


        }

        return new ApiResult<>(0,"SUCCESS");
    }


    /**
     * 取消订单
     *
     * @return
     */
    @RequestMapping(value = "/cancel_order_confirm_picking", method = RequestMethod.POST)
    public ApiResult<Integer> cancelOrderConfirm(@RequestBody GeneratePickingReq req , HttpServletRequest request) {
        log.info("取消订单操作"+ JSON.toJSONString(req));
        var result = orderService.cancelOrderConfirm(req.getId());

        //添加系统日志

        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                "/order/order_wait_pick_list","取消拣货单 , id : "+ JsonUtil.objToString(req.getId())+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");
        return new ApiResult<>(result.getCode(), result.getMsg(), result.getData());
    }

    @RequestMapping(value = "/upd_erp_order_return_code", method = RequestMethod.POST)
    public ApiResult<Integer> cancelOrderConfirm(@RequestBody DataRow req) {
        if(StringUtils.isEmpty(req.get("expressCode")))return new ApiResult<>(EnumResultVo.ParamsError.getIndex(),"物流单号不能为空");
        orderService.updErpOrderReturnCode(req.getLong("id"),req.getString("company"),req.getString("expressCode"));
        return new ApiResult<>(0,"成功");
    }

    @RequestMapping(value = "/add_erp_order_return_item", method = RequestMethod.POST)
    public ApiResult<Integer> add_erp_order_return_item(@RequestBody DataRow req) {
        if(StringUtils.isEmpty(req.get("specNum")))return new ApiResult<>(EnumResultVo.ParamsError.getIndex(),"规格编码不能为空");
        var result= orderService.addErpOrderReturnItem(req.getLong("id"),req.getString("specNum"),req.getInt("num"));
        return new ApiResult<>(result.getCode(),result.getMsg());
    }

    @RequestMapping(value = "/douyin_order_sales_view", method = RequestMethod.POST)
    public ApiResult<List<DouYinOrderCountVo>> zhiboOrderGoodView(HttpServletRequest request, @RequestBody DataRow reqData) {

        String startDate = reqData.getString("start");
        String endDate = reqData.getString("end");
        if(StringUtils.isEmpty(startDate)){
            startDate= DateUtil.customizeDate_(15);
        }

        var result = orderService.getDouYinOrderCount(startDate,endDate);
        /* Collections.reverse(list); // 倒序排列*/

        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "SUCCESS", result);

    }

    /***
     * 一件代发（直播）订单导入excel数据解析ajax
     * @param file
     * @param req
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @RequestMapping(value = "/douyin_order_settle_import", method = RequestMethod.POST)
    public com.b2c.entity.api.ApiResult<Integer> zhubo_order_import_excel_settle(@RequestParam("excel") MultipartFile file, HttpServletRequest req) throws IOException, InvalidFormatException {

        String fileName = file.getOriginalFilename();
        String dir = System.getProperty("user.dir");
        String destFileName = dir + File.separator + "uploadedfiles_" + fileName;
//        System.out.println(destFileName);
        File destFile = new File(destFileName);
        file.transferTo(destFile);
        log.info("/***********导入一件代发订单开始，文件后缀" + destFileName.substring(destFileName.lastIndexOf(".")) + "***********/");

        XSSFSheet sheet;
        InputStream fis = null;

        fis = new FileInputStream(destFileName);

        //订单list
        List<Long> orderList = new ArrayList<>();

        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(fis);
            log.info("/***********导入一件代发订单***读取excel文件成功***********/");

            sheet = workbook.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();//最后一行索引
            XSSFRow row = null;

            //订单实体
            for (int i = 1; i <= lastRowNum; i++) {
                row = sheet.getRow(i);
                String orderId = row.getCell(0).getStringCellValue();

                orderList.add(Long.parseLong(orderId));

            }
            orderService.douyinOrderSettle(orderList,1);
        }catch (Exception e){
            log.info("/***********导入一件代发订单***出现异常：" + e.getMessage() + "***********/");
            return new com.b2c.entity.api.ApiResult<>(500, e.getMessage());
        }
        return new com.b2c.entity.api.ApiResult<>(EnumResultVo.SUCCESS.getIndex(),"成功");
    }

}
